package com.novax.ex.activity.provider.controller.inner;

import com.novax.ex.activity.infrastructure.entity.RankSubConfig;
import com.novax.ex.activity.open.api.inner.RankStandingsInnerApi;
import com.novax.ex.activity.open.model.query.RankStandingQuery;
import com.novax.ex.activity.open.model.response.RankStandingsResponse;
import com.novax.ex.activity.provider.controller.BaseActivityController;
import com.novax.ex.activity.provider.service.RankStandingsService;
import com.novax.ex.activity.provider.service.RankSubConfigService;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import java.util.Collections;
import java.util.Objects;

/**
 * @Description:
 * @Author: ChenXi
 * @Date:  2023/11/23 16:02
 **/
@Slf4j
@RestController
public class RankStandingsInnerController extends BaseActivityController implements RankStandingsInnerApi {

    @Resource
    private RankStandingsService rankStandingsService;
    @Resource
    private RankSubConfigService rankSubConfigService;

    @Override
    public ReturnResult<PageUtil<RankStandingsResponse>> page(RankStandingQuery rankStandingQuery) {
        PageUtil<RankStandingsResponse> page = new PageUtil<>(rankStandingQuery);
        page.setCondition(Collections.singletonMap("query", rankStandingQuery));
        rankStandingsService.findPage(page, RankStandingsResponse.class);
        return ReturnResult.success(page);
    }

    @Override
    public ReturnResult<?> updateByExcel(String language, MultipartFile excelFile, Long rankSubId) {
//        // 无开启的主活动则不处理
//        RankConfig rankConfig = rankConfigService.findOpenWithOutTime();
//        if (Objects.isNull(rankConfig)) {
//            return ReturnResult.fail(getInternational(language, InternationalCode.NOT_FOUND));
//        }

        // Check if the file has a valid extension (xls or xlsx)
        String fileName = excelFile.getOriginalFilename();
        if (fileName == null || (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx"))) {
            return ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
        }

        RankSubConfig rankSubConfig = rankSubConfigService.find(rankSubId);
        if (Objects.isNull(rankSubConfig)) {
            return ReturnResult.fail(getInternational(language, InternationalCode.NOT_FOUND));
        }

        boolean flag = rankStandingsService.updateByExcel(excelFile, rankSubId);
        return flag ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS)) :
            ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

}
